'use client';

import { RefreshCw } from 'lucide-react';
import { useState } from 'react';

interface Position {
  tokenId: string;
  totalAmount: number;
  averagePrice: number;
  totalInvested: number;
  positionCount: number;
  currentPrice: number;
  unrealizedPnL: number;
  unrealizedPnLPercent: number;
}

interface PositionsListProps {
  positions: Position[];
  onRefresh: () => void;
}

export default function PositionsList({ positions, onRefresh }: PositionsListProps) {
  const [isRefreshing, setIsRefreshing] = useState(false);

  const handleRefresh = async () => {
    setIsRefreshing(true);
    await onRefresh();
    setIsRefreshing(false);
  };

  const formatNumber = (num: number, decimals: number = 2) => {
    if (Math.abs(num) >= 1e9) return (num / 1e9).toFixed(decimals) + 'B';
    if (Math.abs(num) >= 1e6) return (num / 1e6).toFixed(decimals) + 'M';
    if (Math.abs(num) >= 1e3) return (num / 1e3).toFixed(decimals) + 'K';
    return num.toFixed(decimals);
  };

  const getTotalPnL = () => {
    return positions.reduce((sum, pos) => sum + pos.unrealizedPnL, 0);
  };

  const getTotalInvested = () => {
    return positions.reduce((sum, pos) => sum + pos.totalInvested, 0);
  };

  const getTotalPnLPercent = () => {
    const totalInvested = getTotalInvested();
    if (totalInvested === 0) return 0;
    return (getTotalPnL() / totalInvested) * 100;
  };

  return (
    <div className="space-y-6">
      {/* 头部统计 */}
      <div className="flex justify-between items-center">
        <h2 className="text-2xl font-bold text-gray-900 dark:text-white">
          持仓信息
        </h2>
        <button
          onClick={handleRefresh}
          disabled={isRefreshing}
          className="btn-primary flex items-center space-x-2"
        >
          <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
          <span>刷新</span>
        </button>
      </div>

      {/* 总览卡片 */}
      {positions.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="card">
            <div className="text-sm text-gray-500 dark:text-gray-400">总持仓数</div>
            <div className="text-2xl font-bold text-gray-900 dark:text-white">
              {positions.length}
            </div>
          </div>
          <div className="card">
            <div className="text-sm text-gray-500 dark:text-gray-400">总投入</div>
            <div className="text-2xl font-bold text-gray-900 dark:text-white">
              ${formatNumber(getTotalInvested())}
            </div>
          </div>
          <div className="card">
            <div className="text-sm text-gray-500 dark:text-gray-400">未实现盈亏</div>
            <div className={`text-2xl font-bold ${
              getTotalPnL() >= 0 ? 'text-green-600' : 'text-red-600'
            }`}>
              {getTotalPnL() >= 0 ? '+' : ''}${formatNumber(getTotalPnL())}
            </div>
          </div>
          <div className="card">
            <div className="text-sm text-gray-500 dark:text-gray-400">总收益率</div>
            <div className={`text-2xl font-bold ${
              getTotalPnLPercent() >= 0 ? 'text-green-600' : 'text-red-600'
            }`}>
              {getTotalPnLPercent() >= 0 ? '+' : ''}{getTotalPnLPercent().toFixed(2)}%
            </div>
          </div>
        </div>
      )}

      {/* 持仓列表 */}
      <div className="card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="table">
            <thead>
              <tr>
                <th>代币</th>
                <th>持仓数量</th>
                <th>平均成本</th>
                <th>当前价格</th>
                <th>总投入</th>
                <th>当前价值</th>
                <th>未实现盈亏</th>
                <th>收益率</th>
                <th>建仓次数</th>
              </tr>
            </thead>
            <tbody>
              {positions.map((position) => {
                const currentValue = position.totalAmount * position.currentPrice;
                return (
                  <tr key={position.tokenId} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                    <td>
                      <div className="font-medium">
                        {/* 这里需要从tokenId获取token信息，暂时显示ID */}
                        Token #{position.tokenId.slice(0, 8)}...
                      </div>
                    </td>
                    <td>
                      <div className="font-mono">
                        {formatNumber(position.totalAmount, 4)}
                      </div>
                    </td>
                    <td>
                      <div className="font-mono">
                        ${position.averagePrice.toFixed(6)}
                      </div>
                    </td>
                    <td>
                      <div className="font-mono">
                        ${position.currentPrice.toFixed(6)}
                      </div>
                    </td>
                    <td>
                      <div className="font-mono">
                        ${formatNumber(position.totalInvested)}
                      </div>
                    </td>
                    <td>
                      <div className="font-mono">
                        ${formatNumber(currentValue)}
                      </div>
                    </td>
                    <td>
                      <div className={`font-mono font-bold ${
                        position.unrealizedPnL >= 0 ? 'text-green-600' : 'text-red-600'
                      }`}>
                        {position.unrealizedPnL >= 0 ? '+' : ''}${formatNumber(position.unrealizedPnL)}
                      </div>
                    </td>
                    <td>
                      <div className={`font-mono font-bold ${
                        position.unrealizedPnLPercent >= 0 ? 'text-green-600' : 'text-red-600'
                      }`}>
                        {position.unrealizedPnLPercent >= 0 ? '+' : ''}{position.unrealizedPnLPercent.toFixed(2)}%
                      </div>
                    </td>
                    <td>
                      <span className="status-indicator bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
                        {position.positionCount}次
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {positions.length === 0 && (
          <div className="text-center py-12">
            <p className="text-gray-500 dark:text-gray-400">
              暂无持仓数据
            </p>
          </div>
        )}
      </div>

      {/* 风险提示 */}
      {positions.length > 0 && (
        <div className="card bg-yellow-50 dark:bg-yellow-900 border-yellow-200 dark:border-yellow-700">
          <h3 className="text-lg font-medium text-yellow-900 dark:text-yellow-100 mb-3">
            风险提示
          </h3>
          <ul className="space-y-2 text-sm text-yellow-800 dark:text-yellow-200">
            <li>• 以上数据为未实现盈亏，实际交易可能存在滑点和手续费</li>
            <li>• Meme币价格波动极大，请注意风险控制</li>
            <li>• 建议设置止损策略，避免过度亏损</li>
            <li>• 定期检查持仓状况，及时调整策略参数</li>
          </ul>
        </div>
      )}
    </div>
  );
}
